
import Common from '../../../public/actions/employing/common';
import ProcessTemplate from './processTemplate';
import moment from 'moment';

import {getQueryCondition} from '../../../../hrpub/common/utils/utils';

export default class BatchAddAction extends Common {

    constructor(comp) {
        super();
        this.comp = comp;
    }

    extend = [ProcessTemplate];

    historyState = null;

    // 打开批量新增弹窗
    openBatchModal = () => {
        this.update({
            batchAddModalVisible: true
        });
    }

    // 关闭批量新增弹窗
    closeBatchModal = () => {
        this.update({
            batchAddModalVisible: false,
            batchAddCurrentStep: 0
        });

        this.comp.setState({
            selectAll: false
        });
    }

    // 打开批量新增的查询台窗
    openBatchAddSearchModal = () => {
        const {props} = this.comp;
        const {search, meta} = props;
        let template = meta.getMeta();

        // 给批量添加弹窗的查询弹窗添加条件
        this.addQueryConditionToMultiAddSearch(template, 'multiadd');

        search.openAdvSearch('multiadd', true);
    }

    // 查询的包裹函数，为了解决查询不能是sync函数的问题
    toSearchWrapper = () => {
        this.toSearch();
    }

    // 拼装查询的参数
    makeSearchOption = () => {
        const {props} = this.comp;
        const {emp, search, meta} = props;
        const template = meta.getMeta();

        let postData = {
            ...getQueryCondition(props, 'multiadd'),
            listpks: this.getExistPks(),
            oid: template['multiadd'].oid,
            pk_org: emp.orgValue.refpk
        };

        return postData
    }

    // 根据查询条件获取批量新增弹窗的表格数据的请求
    postSearchResultTableData = async (postData) => {
        const {props} = this.comp;
        const {dispatch} = props;

        try {
            let res = await dispatch({
                type: 'emp/getBatchAddTableDataBySearch',
                payload: {
                    postData: postData
                }
            });

            return res;
        }
        catch(e) {
            console.error(e);
        }

        return {
            success: false
        };
    }

    // 批量新增弹窗第一步条件选择查询弹窗点击确认
    toSearch = async () => {
        let postData = this.makeSearchOption();
        let res = await this.postSearchResultTableData(postData);
        
        if(res.success && res.data && res.data.psninfo) {
            this.addonRowToTable(res.data.psninfo.rows);
        }
    }

    // 获取已存在的listpks
    getExistPks = () => {
        const {props} = this.comp;
        const {editTable} = props;

        let tableData = editTable.getAllRows('psninfo');

        let listpks = tableData.map((item) => {
            return item.values['pk_psnjob'].value;
        });

        return listpks.join(',')
    }

    // 拼装根据参照获取数据的参数
    makeGetDataByReferOption = (value) => {
        const {props} = this.comp;
        const { emp} = props;

        let postData = {
            listpks: this.getExistPks(),
            pk_org: emp.orgValue.refpk,
            refpks: ''
        };

        let refpks = value.map((item) => {
            return item.refpk;
        });
        postData['refpks'] = refpks.join(',');

        return postData
    }

    // 根据选择的参照进行数据请求
    postResultTableDataByRefer = async (postData) => {
        const {props} = this.comp;
        const {dispatch, emp} = props;

        try {
            let res = await dispatch({
                type: 'emp/getBatchAddTableDataByRefer',
                payload: {
                    postData: postData
                }
            });

            return res;
        }
        catch(e) {
            console.error(e);
        }

        return {
            success: false
        };
    }

    // 批量新增弹窗第一步参照选择逻辑
    changePersonRefer = async (value) => {
        let postData = this.makeGetDataByReferOption(value);
        let res = await this.postResultTableDataByRefer(postData);

        if(res.data && res.data.confirmMsg) {
            this.toast({
                color: 'danger',
                content: res.data.confirmMsg
            });
        }

        if(res.success && res.data && res.data.psninfo) {
            this.addonRowToTable(res.data.psninfo.rows);
        }
    }

    // 在表格后面追加行
    addonRowToTable = (rows) => {
        const {props} = this.comp;
        const {editTable} = props;

        let dataList = editTable.getAllRows('psninfo');

        dataList = dataList.concat(rows);
        editTable.setTableData('psninfo', {rows: dataList}, false);

        this.comp.setState({
            selectAll: false
        });
    }

    // 获取并存储选择的行
    getSelectedRows = () => {
        const {props, state} = this.comp;
        const {editTable, emp} = props;

        let selectedRows = [];

        if(state.selectAll) {
            selectedRows = editTable.getAllRows('psninfo');
        }
        else {
            selectedRows = editTable.getCheckedRows('psninfo').map((item) => {
                return item.data
            });
        }

        this.comp.setState({
            selectRows: this.deepCopy(selectedRows)
        });

        if(selectedRows && selectedRows.length <= 0) {
            this.toast({
                color: 'warning',
                content: emp.language['gx6008-000065'] //'请选择要入职的人员!'
            });
        }

        return selectedRows;
    }

    // 设置批量添加弹窗第二步骤表单的申请日期默认值
    setFormApplyDate = () => {
        const {props} = this.comp;
        const {form} = props;

        form.setAllFormValue({
            entryinfo: {
                rows: [{
                    values: {
                        apply_date: {
                            value: moment().format('YYYY-MM-DD'),
                            display: moment().format('YYYY-MM-DD')
                        }
                    }
                }]
            }
        });
    }

    // 批量添加弹窗点击下一步
    goToNextStep = async () => {
        const {props} = this.comp;
        const {editTable, form} = props;

        this.historyState = this.deepCopy(editTable.getAllRows('psninfo'));

        let selectRows = this.getSelectedRows();

        if(selectRows.length > 0) {
            await this.update({
                batchAddCurrentStep: 1
            });

            form.setFormStatus('entryinfo', 'edit');
            this.setFormApplyDate();
        }
    }

    // 批量添加弹窗点击上一步
    goToPrevStep = () => {
        const {props} = this.comp;
        const {editTable} = props;

        this.update({
            batchAddCurrentStep: 0
        });

        if(this.historyState) {
            editTable.setTableData('psninfo', {rows: this.historyState}, false);
            this.historyState = null;
        }
    }

    // 当表格选择全部的时候
    selectedAll = (...args) => {
        this.comp.setState({
            selectAll: args[2]
        });
    }

    // 选中一行
    selectRow = (...args) => {
        const {
            props: {
                editTable
            }
        } = this.comp;

        let tableData = editTable.getAllRows('psninfo');
        let checkedData = editTable.getCheckedRows('psninfo');

        this.comp.setState({
            selectAll: tableData.length === checkedData.length
        });
    }

    // 拼装表单编辑前请求的参数
    makeFormEditBeforeOption = (key) => {
        const {props} = this.comp;
        const {emp} = props;

        let postData = {
            key: key,
            pk_org: emp.orgValue.refpk
        };

        return postData;
    }

    // 发起表单编辑前请求
    postEditBefore = async (postData) => {
        const {props, state} = this.comp;
        const {emp, dispatch, meta} = props;

        try {
            let res = await dispatch({
                type: 'emp/batchAddModalFormEditBefore',
                payload: {
                    postData: postData
                }
            });

            return res;
        }
        catch(e) {
            console.error(e);
        }
    }

    // 给模版里的字段添加queryCondition
    addQueryConditionToTemplateItem = (formId, key, queryCondition = {}) => {
        const {props} = this.comp;
        const {meta} = props;

        let template = meta.getMeta();

        template[formId].items.map((item) => {
            if(item.attrcode === key) {
                Object.assign(item.queryCondition, queryCondition);
            }
        });
    }

    // 第二步表单编辑前
    formBeforeEdit = async (fprops, moduleId, key, value, data) => {
        const {props} = this.comp;
        const {meta} = props;

        let postData = this.makeFormEditBeforeOption(key);

        try {
            let res = await this.postEditBefore(postData);

            if(res.success) {

                if(res.data && res.data.refParam) {
                    this.addQueryConditionToTemplateItem('entryinfo', key, res.data.refParam);
                }

                await new Promise((resolve, reject) => {
                    let template = meta.getMeta();
                    meta.setMeta(template, resolve);
                });
            }
        }
        catch(e) {
            console.error(`formBeforeEdit: ${e}`);
        }
        return true;
    }

    // 拼装弹窗第二步表单编辑后请求参数
    makeFormEditAfterOption = (key) => {
        const {props, state} = this.comp;
        const {emp, dispatch, meta, form} = props;

        let postData = {
            key: key,
            model: form.getAllFormValue('entryinfo'),
            pk_org: emp.orgValue.refpk
        };

        return postData;
    }

    // 发起表单编辑后的请求
    postEditAfter = async (postData) => {
        const {props, state} = this.comp;
        const {emp, dispatch, meta, form} = props;

        try {
            let res = await dispatch({
                type: 'emp/batchAddModalFormEditAfter',
                payload: {
                    postData: postData
                }
            });

            return res;
        }
        catch(e) {
            console.error(e);
        }
    }

    // 批量新增弹窗第二步编辑后
    formAfterEdit = async (fprops, moduleId, key, value, data) => {
        const {props} = this.comp;
        const {form} = props;

        let postData = this.makeFormEditAfterOption(key);

        let res = this.postEditAfter(postData);

        if(res.success) {
            form.setAllFormValue({
                entryinfo: res.data.entryinfo
            });
        }
    }

    // 拼接完成批量新增请求参数
    makeSubmitBatchAddOption = () => {
        const {props, state} = this.comp;
        const {emp, form} = props;

        let postData = {
            listpks: '',
            model: form.getAllFormValue('entryinfo'),
            pk_org: emp.orgValue.refpk
        };

        let listpks = state.selectRows.map((item) => {
            return item.values['pk_psnjob'].value
        });

        postData['listpks'] = listpks.join(',');
        
        return postData;
    }

    // 发起完成批量新增请求
    postSubmitBatchAdd = async (postData) => {
        const {props, state} = this.comp;
        const {dispatch} = props;

        try {
            let res = await dispatch({
                type: 'emp/batchAddModalSubmit',
                payload: {
                    postData: postData
                }
            });

            return res;
        }
        catch(e) {
            console.error(e);
        }
    }

    // 批量新增弹窗点击完成
    submitBatchAdd = async () => {
        const {props} = this.comp;
        const {emp, form} = props;

        if(!form.isCheckNow('entryinfo')) {
            return;
        }

        let postData = this.makeSubmitBatchAddOption();

        let res = await this.postSubmitBatchAdd(postData);

        if(res.success) {
            this.toast({
                color: 'success',
                content: emp.language['gx6008-000066'] // 新增成功
            });
            this.closeBatchModal();
            this.pubSub.publish('getMainTableData');
        }
    }
}